<script setup lang="ts">
import type { FormInst, FormRules } from 'naive-ui'
import type { ModelType } from './viewModel/baseInfoModel'
import type { IFormItem } from '@/components/NFormBuilder/types.d.ts'
import { useTemplateRef } from 'vue'
import baseInfoModel from './viewModel/baseInfoModel'
import NFormBuilder from '@/components/NFormBuilder/index.vue'
defineOptions({
  name: 'BaseInfo',
})
const queryForm = ref<ModelType>(baseInfoModel.getData())
const formItems = ref<IFormItem[]>([
  {
    label: '昵称',
    field: 'nickname',
  },
  {
    label: '用户名',
    field: 'username',
    props: {
      disabled: true,
    },
  },
  {
    label: '姓名',
    field: 'name',
  },
  {
    label: '手机号',
    field: 'phone',
  },
])
const rules: FormRules = baseInfoModel.getRules()
const ruleForm = useTemplateRef<FormInst | null>('ruleForm')
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault()
  ruleForm.value?.validate((errors) => {
    if (!errors) {
      baseInfoModel
        .save(queryForm.value)
        .then(() => {
          msgUtil.$message.success('修改成功')
        })
        .catch((err) => {
          msgUtil.$message.error(err.message)
        })
    }
  })
}

const updAvatar = (url: string) => {
  queryForm.value.avatar = url
  baseInfoModel
    .save(queryForm.value)
    .then(() => {
      msgUtil.$message.success('修改成功')
    })
    .catch((err) => {
      msgUtil.$message.error(err.message)
    })
}
defineExpose({
  updAvatar,
})
</script>
<template>
  <div class="form">
    <n-form-builder ref="ruleForm" v-model="queryForm" :form-items="formItems" :rules="rules" />
    <n-button type="primary" attr-type="button" @click="handleValidateClick">
      <span>提交</span>
    </n-button>
  </div>
</template>

<style scoped lang="scss">
.form {
  padding-bottom: 20px;
}
</style>
